'''
Created on 2012-9-11

@author: Administrator
'''
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import images  

from common.sessions import Session
from model.models import Blog
from common.util import Logger
from common import util
from model import models

logger_ = Logger()

class SaveNewBlogPervlet( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        self.session = Session()
        try :
            self.session['username']
            self.session['key']
        except KeyError :
            logger_.info( str( KeyError ) )
            self.redirect( 'login.html', True )
            return
        
        title = self.request.get( 'title' )
        catelog = self.request.get( 'catelog' )
        #picture = self.request.get( 'picture' )  TODO
        text = self.request.get( 'text' )
        blog = Blog( user = self.session['key'], title = title, catelog = catelog, text = text )
        blog.put()
        logger_.info( 'add new user blog into datastore!', '\ntitle : ' + title.encode( 'utf-8' ) + '\n catelog : ' + catelog.encode( 'utf-8' ) + '\n text : ' + text.encode( 'utf-8' ) )
        self.redirect( 'login', True )

class DeleteBlogPervlet( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        logger_.info( "delete blog" )
        self.session = Session()
        try :
            self.session['username']
            self.session['key']
        except KeyError :
            logger_.info( str( KeyError ) )
            self.redirect( 'login.html', True )
            return
        
        title = self.request.get( 'title' )
        catelog = self.request.get( 'catelog' )
        key = self.request.get( 'key' )
        models.delete_by_pk( Blog, key )
        self.redirect( 'login', True )
        
class ContactMeHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        #check weather user login, if so, using user email, if not, using guest email
        #TODO
        name = self.request.get( "guest_name" )
        email = self.request.get( "guest_email" )
        mircroblog = self.request.get( "guest_microblog" )
        comments = self.request.get( "contact_comments" )
        contact_request = models.ContactRequest( name = name, email = email, mircroblog = mircroblog, comments = comments )
        try:
            contact_request.put()
            self.redirect( "contact.html?result=success", True )
            logger_.error( "store contact request success!" )
        except Exception, e:
            self.redirect( "contact.html?result=500", True )
            logger_.error( "store contact request error!", e.__name__ + ":" + e.message )

class BlogComment( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        '''
            blog id is formated like "blog|blog.catelog|blog.title"
        '''
        blogid = self.request.get( 'blogid' )
        index_1 = blogid.find( '|' )
        index_2 = blogid.rfind( '|' )
        catelog = blogid[index_1 + 1:index_2]
        title = blogid[index_2 + 1:]
        logger_.info( "comment on blog , catelog :  " + catelog + ", title : " + title )
        
        #find the blog which is commented.
        blog_of_comment = models.get_tuple_by_key( models.Blog, 1, 0, catelog = catelog, title = title )[0]
        
        logger_.info( util._TEST_STRING )
        name = self.request.get( 'name' )
        email = self.request.get( 'email' )
        website = self.request.get( 'website' )
        comment = self.request.get( 'comment' )
        logger_.info( "comment info : name : " + name.encode( 'utf-8' ) + ", email: " + email.encode( 'utf-8' ) + ", website:" + website.encode( 'utf-8' ) + ", comment: " + comment.encode( 'utf-8' ) )
        logger_.info( util._TEST_STRING + "123" )
        
        #create a user object, try to find it in db, if it doesn't exist, put it into db
        user_of_comment = models.User( username = "", nickname = name, email = email, website = website )
        if  not models.check_for_exist( models.User, email = email ):
            user_of_comment.put()
        else:
            temp_tuple = models.get_tuple_by_key( models.User, 30, 0, nickname = name, email = email, website = website )
            if len( user_of_comment = temp_tuple ) > 1:
                for user in temp_tuple:
                    logger_.error( "User duplicated! user key : " + user.key() )
            else:
                user_of_comment = temp_tuple[0]
        
        
        #create a BlogComment object, build restrain.
        #now, it doesn't support comment reference to other one.
        comment_obj = models.BlogComment( user = user_of_comment.key(), blog = blog_of_comment.key() , text = comment )
        comment_obj.put()
        
        #TODO call back info : success or fail
        self.redirect( 'blog.html?result=success', True )


class PictureExhibiter( webapp.RequestHandler ):
    '''
        @param reqkind: 1. gallery model 2.close-up model 3. apply picture to blog 4.user avatar
    '''
    
    def get( self ):
        self.post()
        
    def post( self ):
        request_kind = self.request.get( 'reqkind' ).strip()
        life_key = self.request.get( 'life.uuid' )
        
        if request_kind == '1':
            # 1 means gallery model(100:120)
            life = db.Query( models.Life ).filter( "__key__ =", db.Key( life_key ) ).get()
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write( life.pictureblob )
            
        elif request_kind == '2':
            # 2 means close-up model (original one)
            life = db.Query( models.Life ).filter( "__key__ =", db.Key( life_key ) ).get()
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write( life.pictureoriginal )
        elif request_kind == '3':
            # 3 means applying picture to blog
            life_key = self.request.get( 'life_key' )
            blog_key = self.request.get( 'blog_key' )
            blog = db.Query( models.Blog ).filter( '__key__', db.Key( blog_key ) ).get()
            blog.picture = life_key
            blog.put()
            self.redirect( '/login', True )
        elif request_kind == '4':
            # show user avatar
            user_key = self.request.get( 'user_key' )
            user = db.Query( models.User ).filter( "__key__ =", db.Key( user_key ) ).get()
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write( user.avatar )
        else:
            logger_.error( 'error request parameter : "reqkind" is "",ignored request' )
            return
        


class PictureUploader( webapp.RequestHandler ):
    WANNA_RATIO_ = 0.833333 # icon width : height | 100 : 120
    MAX_RATIO_ = 0.913043 # 105 : 115
    MIN_RATIO_ = 0.76 # 95 : 125
    def get( self ):
        self.post()
        
    def post( self ):
        if not check_session( self ):
            self.redirect( 'login', True )
            return
        image = self.request.get( 'picture' )
        reqkind = self.request.get( 'reqkind' )
        '''
            reqkind : 1. user avatar
        '''
        
        try:
            image_ = images.Image( image )
        except Exception, e:
            logger_.error( 'exception occurred!!!!!!', "Exception message : " + str( e ) )
            self.redirect( '/login', True )
            return
        
        from decimal import Decimal 
        i_width = Decimal( image_.width )
        i_height = Decimal( image_.height )
        w_h_ratio = i_width / i_height 
        if PictureUploader.MIN_RATIO_ > w_h_ratio: # picture too narrow
            h_ratio = i_height / 120
            expected_w = Decimal( "%.6f" % ( i_width / h_ratio ) )
            image_ = images.resize( image, int( expected_w ), 120 )
        elif PictureUploader.MAX_RATIO_ < w_h_ratio: # picture too short
            w_ratio = i_width / 100
            expected_h = Decimal( "%.6f" % ( i_height / w_ratio ) )
            image_ = images.resize( image, 100, int( expected_h ) )
        else:
            image_ = images.resize( image, 100, 120 )
        comment = self.request.get( 'comment' ).strip()
        if reqkind == '1':
            user = models.get_by_pk( models.User, self.session['key'] )
            user.avatar = image_
            user.put()
        else:
            models.Life( user = self.session['key'], pictureblob = image_, comment = comment ).put()
        
        self.redirect( '/login', True )
        
        '''
        image = self.request.get('picture')
        image_ = images.Image( image )
        h = image_.height
        w = image_.width
        icon_image = db.Blob(image)
        life = models.Life()
        life.pictureblob = icon_image
        
        life.put()
        self.redirect('/login', True)  
        '''

class LifeDeleter( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        uuid = self.request.get( 'uuid' ).strip()
        if uuid == '':
            logger_.info( 'invalid key' )
            self.redirect( 'login', True ) 
            return
        logger_.info( 'delete life by key : ' + uuid )
        db.Query( models.Life ).filter( '__key__', db.Key( uuid ) ).fetch( 1 )[0].delete()   
        self.redirect( 'login', True ) 

class Deleter( webapp.RequestHandler ):
    '''
            # T O D O
    '''
    def get( self ):
        self.post()
    
    def post( self ):
        if not check_session( self ):
            self.redirect( 'login.html', True )
            return

        key_code = self.request.get( 'uuid' )
        
        
def check_session( handler ):
    flag = False
    handler.session = Session()
    try :
        handler.session['username']
        handler.session['key']
        flag = True
    except KeyError :
        pass
    logger_.log_submodel( "pervlets.check_session", str( flag ) )
    return flag
    
    
    
    
    
    
    
    
    
    
    
    
    
